package com.qianniu.napi.common.util;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class ColorUtil {


    // 主题配对色Key对应frontColor  value对应bgColor
    public static Map<String,String> colorMap = new HashMap<String,String>();
    static {
        colorMap.put("6497C7","ECF8FF");
        colorMap.put("709A7B","F0FDF0");
        colorMap.put("E9DEC3","2B96AC");
    }

    public static void main(String[] args) {
        System.out.println(toHexStr(new Color(Integer.parseInt("f0fdf0", 16))));
        System.out.println(toColor(toHexStr(Color.BLUE)));
    }

    /**
     * Color对象转换成字符串
     * @param color Color对象
     * @return 16进制颜色字符串
     * */
    public static String toHexStr(Color color){
        String r,g,b;
        StringBuilder su = new StringBuilder();
        r = Integer.toHexString(color.getRed());
        g = Integer.toHexString(color.getGreen());
        b = Integer.toHexString(color.getBlue());
        r = r.length() == 1 ? "0" + r : r;
        g = g.length() ==1 ? "0" +g : g;
        b = b.length() == 1 ? "0" + b : b;
        r = r.toUpperCase();
        g = g.toUpperCase();
        b = b.toUpperCase();
        su.append("#");
        su.append(r);
        su.append(g);
        su.append(b);
        //#0000FF
        return su.toString().toUpperCase();
    }

    /**
     * Color对象转换成十进制json
     * @param colorStr Color对象
     * @return 16进制颜色字符串
     * */
    public static RGB toRGB( String colorStr ){
        String r,g,b;

        Color color = toColor(colorStr);
        r = String.valueOf(color.getRed());
        g = String.valueOf(color.getGreen());
        b = String.valueOf(color.getBlue());
        RGB rgb = new RGB(r,g,b);

        return rgb;
    }

    /**
     * 字符串转换成Color对象
     * @param colorStr 16进制颜色字符串
     * @return Color对象
     * */
    public static Color toColor(String colorStr){

        colorStr = getColorStr(colorStr);
        Color color =  new Color(Integer.parseInt(colorStr, 16));
        return color;
    }



    /**
     * 字符串转换成主题配对的Color对象
     * @param colorStr 16进制颜色字符串
     * @return Color对象
     * */
    public static Color toThemeColor(String colorStr){

        colorStr = getColorStr(colorStr);
        Color color =  new Color(Integer.parseInt(colorMap.get(colorStr), 16)) ;
        return color;
    }

    private static String getColorStr(String colorStr){
        if(colorStr.indexOf("#")>=0)colorStr = colorStr.replace("#","");
        if(colorStr.indexOf("0x")>=0)colorStr = colorStr.replace("0x","");
        if(colorStr.length()>6)colorStr = colorStr.substring(colorStr.length()-6);
        if(colorStr.length()==3){
            StringBuffer sb = new StringBuffer();
            for(char item: colorStr.toCharArray()){
                sb.append(item);
                sb.append(item);
            }
            colorStr = sb.toString();
        }
        return colorStr.toUpperCase();
    }
}
